<template>
  <div class="app-container">
    <!-- 高级查询 -->
    <el-form v-show="searchVisible" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="商城:">
        <el-select v-model="queryParams.mallCustNo" placeholder="请选择商城编号" clearable size="small">
          <el-option v-for="option in options.mallOptions" :key="option.id" :label="option.customerName" :value="option.id" />
        </el-select>
      </el-form-item>
     <!-- <el-form-item label="供应商编号:">
        <el-select v-model="queryParams.supplierNo" placeholder="请选择供应商编号" clearable size="small">
          <el-option v-for="option in options.supplierIdOptions" :key="option.id" :label="option.supplierName" :value="option.id" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="店铺:">
        <el-select v-model="queryParams.storeId" placeholder="请选择店铺编号" clearable size="small">
          <el-option v-for="option in options.storeOptions" :key="option.id" :label="option.storeName" :value="option.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="商城SKU:">
        <el-input v-model="queryParams.csaSkuCode" size="small" placeholder="请输入商城SKU" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品名称:">
        <el-input v-model="queryParams.custGoodsName" size="small" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
    <el-form-item label="商城SPU:">
        <el-input v-model="queryParams.csaSpuCode" size="small" placeholder="请输入商品编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="品牌:">
       <el-select v-model="queryParams.brandId" placeholder="请选择品牌" clearable size="small" >
          <el-option v-for="boption in options.brands" :key="boption.id" :label="boption.brandName" :value="boption.id"  />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
    <!--  <el-col :span="1.5">
        <el-button v-hasPermission="['accounting:materialBuyPrice:insert']" type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button v-hasPermission="['accounting:materialBuyPrice:update']" type="success" icon="el-icon-edit" size="mini" :disabled="isSingle" @click="handleEdit">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermission="['accounting:materialBuyPrice:delete']" type="danger" icon="el-icon-delete" size="mini" :disabled="isMultiple" @click="handleRemove">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermission="['accounting:materialBuyPrice:update']" type="info" icon="el-icon-upload2" size="mini" @click="openUploadDialog">历史数据导入</el-button>
      </el-col>
      <pagination v-show="page.total>0" :total="page.total" :page.sync="page.current" :limit.sync="page.pageSize" @pagination="handleQuery" />

  <!--    <right-toolbar :show-search.sync="searchVisible" @queryTable="handleQuery" />
  -->  </el-row>

    <!-- 数据列表 -->
    <el-table v-loading="loading" :data="page.records" highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商城商品编码" width="115" align="center" prop="csaSpuCode" />
       <el-table-column label="商城SKUID" width="115" align="center" prop="csaSkuCode" />
       <el-table-column label="商品名称" width="235" align="center" prop="custGoodsName" />
       <el-table-column label="品牌" align="center" prop="brandName" />
       <el-table-column label="店铺"  width="135"  align="center" prop="storeName" />
       <el-table-column label="供货价" align="right" prop="settlePrice" />
       <el-table-column label="与营销委结算价" align="center" prop="custRelSalesPrice" />
       <el-table-column label="单品/组合" align="center" prop="groupOrSpu" />

        <el-table-column label="有效始" align="center" prop="applyDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.applyDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
         <el-table-column label="里程价格" width="90" align="right" prop="custMileSalesPrice" />
        <el-table-column label="供应商"  width="135" align="center" prop="supplierName" />
       <el-table-column label="商城" align="center" prop="mallName" />
       <el-table-column label="加价比例" align="center" prop="addPriceRate" />
       <el-table-column label="货号" align="center" prop="custGoodsNo" />
       <el-table-column label="规格" align="center" prop="materialGuige" />
       <el-table-column label="常规品活动品" align="center" prop="regularOrDisCt" />
       <el-table-column label="自营" align="center" prop="selfBusinessYn" />

       <el-table-column label="有效至" align="center" prop="effectUntilDate" width="180">
         <template slot-scope="scope">
           <span>{{ parseTime(scope.row.effectUntilDate, '{y}-{m}-{d}') }}</span>
         </template>
       </el-table-column>
       <el-table-column label="价差比例" align="right" prop="priceDiffRate" />

       <el-table-column label="京东售价" align="right" prop="jdSalesPrice" />


       <el-table-column label="仓库" align="center" prop="warehouse" />
       <el-table-column label="产地" align="center" prop="originLocation" />
       <el-table-column label="品牌名称" align="center" prop="brandName" />
       <el-table-column label="库存" align="center" prop="inventory" />
       <el-table-column label="吊牌价" align="right" prop="suggestRetailerPrice" />
       <el-table-column label="销量" align="right" prop="estCurrentSaleQty" />
       <el-table-column label="备注" align="center" prop="remark" />
       <el-table-column label="创建时间" align="center" prop="createTime" width="180">
         <template slot-scope="scope">
           <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
         </template>
       </el-table-column>
      <!-- <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermission="['order:salesOrder:insert']" size="mini" type="text" icon="el-icon-delete" @click="handleRemove(scope.row)">删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <!-- 分页 -->

    <!-- 添加/修改对话框 -->
    <el-dialog :title="materialBuyPriceFormDialog.title" :visible.sync="materialBuyPriceFormDialog.visible" :close-on-click-modal="false" :before-close="resetMaterialBuyPriceFormDialog" width="500px" append-to-body>
      <el-form ref="materialBuyPriceForm" :model="materialBuyPriceFormData" :rules="materialBuyPriceFormRules" label-width="80px">
      <el-form-item label="商品名称" prop="custGoodsName">
        <el-input v-model="materialBuyPriceFormData.custGoodsName" placeholder="请输入商品名称" />
      </el-form-item>
      <el-form-item label="店铺" prop="storeName">
        <el-input v-model="materialBuyPriceFormData.storeName" placeholder="请输入店铺" />
      </el-form-item>
       <el-form-item label="供货价" prop="settlePrice">
         <el-input v-model="materialBuyPriceFormData.settlePrice" placeholder="请输入供货价" />
       </el-form-item>
       <el-form-item label="货号" prop="custGoodsNo">
         <el-input v-model="materialBuyPriceFormData.custGoodsNo" placeholder="请输入货号" />
       </el-form-item>
       <el-form-item label="商品编码" prop="csaSpuCode">
         <el-input v-model="materialBuyPriceFormData.csaSpuCode" placeholder="请输入商城商品编码" />
       </el-form-item>
       <el-form-item label="商城SKU" prop="csaSkuCode">
         <el-input v-model="materialBuyPriceFormData.csaSkuCode" placeholder="请输入商城SKUID" />
       </el-form-item>
       <el-form-item label="时间始" prop="applyDate">
         <el-date-picker v-model="materialBuyPriceFormData.applyDate" type="date" value-format="yyyy-MM-dd" size="small" style="width: 200px" placeholder="选择应用时间开始" clearable />
       </el-form-item>
       <el-form-item label="有效期至" prop="effectUntilDate">
         <el-date-picker v-model="materialBuyPriceFormData.effectUntilDate" type="date" value-format="yyyy-MM-dd" size="small" style="width: 200px" placeholder="选择有效期至" clearable />
       </el-form-item>
       <el-form-item label="品牌ID" prop="brandId">
         <el-input v-model="materialBuyPriceFormData.brandId" placeholder="请输入品牌ID" />
       </el-form-item>
       <el-form-item label="品牌名称" prop="brandName">
         <el-input v-model="materialBuyPriceFormData.brandName" placeholder="请输入品牌名称" />
       </el-form-item>
       <el-form-item label="产品规格" prop="materialGuige">
         <el-input v-model="materialBuyPriceFormData.materialGuige" placeholder="请输入产品规格" />
       </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmMaterialBuyPriceFormDialog">确 定</el-button>
        <el-button @click="resetMaterialBuyPriceFormDialog">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="uploadDialog.title" :visible.sync="uploadDialog.visible" width="400px" append-to-body>
      <div v-loading="uploadLoading">
        <el-upload
          ref="upload"
          :limit="1"
          :headers="uploadData.headers"
          :action="uploadData.url + '?updateSupport=' + uploadData.updateSupport"
          :data="uploadData.params"
          :disabled="uploadData.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-error="handleFileError"
          :auto-upload="false"
          accept=".xlsx, .xls"
          drag
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div slot="tip" class="el-upload__tip">
            <el-select v-model="uploadData.params.mallId" style="width: 100%" filterable clearable placeholder="请选择商城" @change="handleSelectedMall">
              <el-option v-for="option in options.mallOptions" :key="option.id" :label="option.customerName" :value="option.id" />
            </el-select>
            </div>
            <div slot="tip" class="el-upload__tip">
               <el-link type="info" style="font-size:16px" @click="handleDownloadTemplate">下载模板</el-link>
             </div>

          <div slot="tip" class="el-upload__tip" style="color:red">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="confirmUploadDialog">确 定</el-button>
          <el-button @click="resetUploadDialog">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MaterialBuyPriceApi from '@/api/accounting/MaterialBuyPriceApi'
import CustomerApi from '@/api/basic/CustomerApi'
import StoreApi from '@/api/basic/StoreApi'
import SupplierApi from '@/api/basic/SupplierApi'
import AuthUtils from '@/utils/AuthUtils'
import BrandApi from '@/api/goods/BrandApi'
const defaultMaterialBuyPriceFormData = {
  settleUnitType: null,
  supplierNo: null,
  paymentMethod: null,
  settlePrice: null,
  applyDate: null,
  effectUntilDate: null,
  unitName: null,
  categoryId: null,
  categoryName: null,
  brandId: null,
  brandName: null,
  materialGuige: null,
  dimensionOne: null,
  dimensionTwo: null,
  dimensionThree: null,
  dimensionFour: null,
  dimensionFive: null,
  dimensionSix: null,
  dimensionSeven: null,
  dimension: null,
  settleBy: null,
  wholeSaleQuantity: null
}
export default {
  name: 'MaterialBuyPriceList',
  data() {
    return {
      options: {
        mallOptions: [],
        brands: [],
        supplierIdOptions: [], // 供应商编号字典
        storeOptions: [],
        sysYnTypeOptions: this.$constant.sysYnTypeOptions
      },
      queryParams: {
        settleUnitType: null,
        supplierNo: null,
        skuOrSpuId: null,
        paymentMethod: null,
        settlePrice: null,
        applyDate: null,
        effectUntilDate: null,
        unitName: null,
        categoryId: null,
        categoryName: null,
        brandId: null,
        brandName: null,
        materialGuige: null,
        dimensionOne: null,
        dimensionTwo: null,
        dimensionThree: null,
        dimensionFour: null,
        dimensionFive: null,
        dimensionSix: null,
        dimensionSeven: null,
        dimension: null,
        settleBy: null,
        wholeSaleQuantity: null,
        isValid: this.$constant.Y
      },
      page: {
        current: 1,
        pageSize: 10,
        total: 0,
        records: []
      },
      materialBuyPriceFormDialog: {
        title: '',
        visible: false
      },
      materialBuyPriceFormData: Object.assign({}, defaultMaterialBuyPriceFormData),
      materialBuyPriceFormRules: {
      },
      uploadDialog: {
        title: '历史基础数据导入',
        visible: false
      },
      uploadData: {
        headers: { Authorization: 'Bearer ' + AuthUtils.getToken() }, // 上传请求头
        url: process.env.VUE_APP_BASE_API + '/accounting/materialBuyPrice/importExistSpuData', // 上传的地址
        params: {
          mallId: null,
          applyDate: null
        },
        isUploading: false, // 是否禁用上传
        updateSupport: 0 // 是否更新已经存在的数据
      },
      loading: true,
      uploadLoading: false,
      searchVisible: true,
      multipleSelection: [],
      isSingle: true,
      isMultiple: true
    }
  },
  created() {
    this.handleQuery()
    this.loadOptions()
   },
  methods: {
    loadOptions() {
      let  that = this;
      CustomerApi.list().then(response => {
        that.options.mallOptions = response.data
      })
      StoreApi.list().then(response => {
        that.options.storeOptions = response.data
      })
      SupplierApi.list().then(response => {
        that.options.supplierIdOptions = response.data
      })
      BrandApi.list().then(response => {
        that.options.brands = response.data
      })
    },
    handleAdd() {
      this.openMaterialBuyPriceFormDialog()
    },
    handleRemove(row) {
      const ids = row.id || this.multipleSelection.map(item => item.id)
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return MaterialBuyPriceApi.remove(ids)
      }).then(() => {
        this.handleQuery()
        this.$message.success('删除成功')
      })
    },
    handleEdit(row) {
      const id = row.id || this.multipleSelection.map(item => item.id)[0]
      this.openMaterialBuyPriceFormDialog(id)
    },
    handleQuery() {
      this.loading = true
      MaterialBuyPriceApi.page(this.queryParams, this.page).then(response => {
        this.page.records = response.data.records
        this.page.total = response.data.total
        this.loading = false
      }, () => {
        this.loading = false
      })
    },
    handleSelectedMall(mallId) {
      this.uploadData.params.mallId = mallId
      console.log(this.uploadData.params.mallId)
    },
    handleExport() {
      this.$confirm('是否确认导出数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return MaterialBuyPriceApi.exportData(this.queryParams)
      }).then(response => {
        this.$common.download(response.data)
      })
    },
    openMaterialBuyPriceFormDialog(id) {
      this.materialBuyPriceFormDialog.visible = true
      if (id) {
        this.materialBuyPriceFormDialog.title = '供应商采购价格配置基础，用于配置价格，产生最后付款结算。-修改'
        MaterialBuyPriceApi.get(id).then(response => {
          this.materialBuyPriceFormData = {
            ...this.materialBuyPriceFormData,
            ...response.data
          }
        })
      } else {
        this.materialBuyPriceFormDialog.title = '供应商采购价格配置基础，用于配置价格，产生最后付款结算。-添加'
      }
    },
    confirmMaterialBuyPriceFormDialog() {
      this.$refs['materialBuyPriceForm'].validate(valid => {
        if (valid) {
          if (this.materialBuyPriceFormData.id) {
            MaterialBuyPriceApi.edit(this.materialBuyPriceFormData).then(response => {
              this.$message.success('修改成功')
              this.resetMaterialBuyPriceFormDialog()
              this.handleQuery()
            })
          } else {
            MaterialBuyPriceApi.add(this.materialBuyPriceFormData).then(response => {
              this.$message.success('添加成功')
              this.resetMaterialBuyPriceFormDialog()
              this.handleQuery()
            })
          }
        }
      })
    },
    resetMaterialBuyPriceFormDialog() {
      this.materialBuyPriceFormDialog = {
        title: '',
        visible: false
      }
      this.materialBuyPriceFormData = Object.assign({}, defaultMaterialBuyPriceFormData)
      this.resetForm('materialBuyPriceForm')
    },
    openUploadDialog() {
      this.resetUploadDialog()
      this.uploadDialog.visible = true
    },
    confirmUploadDialog() {
      this.uploadLoading = true
      this.$refs.upload.submit()
    },
    resetUploadDialog() {
      this.uploadDialog.visible = false
      this.uploadData.params.mallId = null
    },
    handleDownloadTemplate() {
      MaterialBuyPriceApi.importExistTemplate().then(response => {
        this.$common.download(response.data)
      })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.uploadData.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.uploadLoading = false
      this.uploadDialog.visible = false
      this.uploadData.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.data ? response.data : response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.handleQuery()
    },
    // 文件上传失败处理
    handleFileError(response, file, fileList) {
      this.uploadLoading = false
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      this.isSingle = selection.length !== 1
      this.isMultiple = !selection.length
    },
    resetQuery() {
      this.page.current = 1
    //  this.resetForm('queryForm')
     this.queryParams = {
       mallCustNo: null,
       supplierNo: null,
       storeId: null,
       csaSkuCode: null,
       custGoodsName: null,
       brandId: null,
       csaSpuCode: null,
       brandName: null,
       isValid: this.$constant.Y
     }

      this.handleQuery()
    }
  }
}
</script>
